import { StateCreator } from 'zustand';
import { AppStore } from '.';

type WorldStateItem = {
  key: string;
  value: string;
};

export type WorldStateStore = {
  worldState: WorldStateItem[];
  setWorldState: (item: WorldStateItem[]) => void;
  appendWorldState: (item: WorldStateItem) => void;
  unshiftWorldState: (item: WorldStateItem) => void;
  getWorldState: () => WorldStateItem[];
  initWorldState: () => void;
};

export const worldStateStore: StateCreator<WorldStateStore> = (set, get) => ({
  worldState: [],
  setWorldState: (item) => set((state) => {
    const stat = state as AppStore;
    if(stat.userId){
      localStorage.setItem(`worldState${stat.userId}`,JSON.stringify(item));
    }
    return { worldState: item }
  }),
  initWorldState: () => set((state) => {
    const stat = state as AppStore;
    if(stat.userId){
      const worldStateStr = localStorage.getItem(`worldState${stat.userId}`);
      try{
        const worldState = JSON.parse(worldStateStr||'[]') as WorldStateItem[];
        return { worldState }
      }catch(e){
        return {}
      }
    }
    return {}
  }),
  appendWorldState: (item) => set((state) => ({ worldState: [...state.worldState, item] })),
  unshiftWorldState: (item) => set((state) => ({ worldState: [item, ...state.worldState] })),
  getWorldState: () => get().worldState
});
